package org.csu.sei.common;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;

public class ImageUpload {
    public static String getUrl(String dir,MultipartFile imageUpload) throws OSSException, ClientException, IOException {
        String endpoint= BaseConstant.OSSConfig.END_POINT;
        String accessKeyId= BaseConstant.OSSConfig.ACCESS_KEY_ID;
        String accessKeySercet=BaseConstant.OSSConfig.ACCESS_KEY_SERCET;
        String bucketName=BaseConstant.OSSConfig.BUCKET;
        String objectTemplate="%s/%s.%s";

        //图片名称为 系统获取的毫秒数+1000内的随机数 *md5加密
        int randParam = (int)(Math.random() * 10000);
        String primaryName=""+System.currentTimeMillis()+randParam;
        String name=md5(primaryName);

        //获取上传图片的类型
//        System.out.println(imageUpload.getContentType());
//        System.out.
//        .0println(imageUpload.getName());
        String type=imageUpload.getContentType().split("/")[1];

        //生成符合ossClient参数要求的图片名，如: banner/7c1ed21b0ef41bd5f5331c8295f179cd39db3d12.jpeg
        String objectName= String.format(objectTemplate, dir,name,type);

        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySercet);
        ossClient.putObject(bucketName,objectName,new ByteArrayInputStream(imageUpload.getBytes()));
        ossClient.shutdown();

        //返回图片的url链接
        return BaseConstant.OSSConfig.BASIC_URL+"/"+objectName;
    }

    public static String md5(String text){
        //加密后的字符串
        String encodeStr= DigestUtils.md5DigestAsHex(text.getBytes());
        return encodeStr;
    }

}
